package com.dxp.demo2.druid;


import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.dxp.JdbcConfig;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author carzy
 * @date 2018/09/18
 */
public class DataPool {

    private static final String DRIVER_CLASS_NAME = JdbcConfig.DRIVER_CLASS_NAME;
    private static final String URL = JdbcConfig.URL;
    private static final String USERNAME = JdbcConfig.USERNAME;
    private static final String PASSWORD = JdbcConfig.PASSWORD;

    private final static DataPool DATA_POOL = new DataPool();
    private DruidDataSource dataSource;

    private DataPool() {
        try {
            dataSource = new DruidDataSource();
            dataSource.setUrl(URL);
            dataSource.setDriverClassName(DRIVER_CLASS_NAME);
            dataSource.setUsername(USERNAME);
            dataSource.setPassword(PASSWORD);
            /* 配置初始化大小、最小、最大 **/
            dataSource.setInitialSize(1);
            dataSource.setMinIdle(1);
            dataSource.setMaxActive(10);
            /* 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒 **/
            dataSource.setTimeBetweenEvictionRunsMillis(60000);
            /* 配置一个连接在池中最小生存的时间，单位是毫秒 **/
            dataSource.setMinEvictableIdleTimeMillis(300000);
            dataSource.setTestWhileIdle(true);
            /* 防止取到的连接不可用 **/
            dataSource.setTestOnBorrow(true);
            dataSource.setTestOnReturn(false);
            /* 打开PSCache，并且指定每个连接上PSCache的大小 **/
            dataSource.setPoolPreparedStatements(true);
            dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
            /* 验证连接有效与否的SQL **/
            dataSource.setValidationQuery("select 1 ");
            dataSource.setFilters("stat");
            dataSource.setDefaultAutoCommit(false);
            List<Filter> filters = new ArrayList<>();
            Slf4jLogFilter filter = new Slf4jLogFilter();
            filter.setStatementExecutableSqlLogEnable(false);
            filters.add(filter);
            dataSource.setProxyFilters(filters);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataPool getInstance() {
        return DATA_POOL;
    }

    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void stop() {
        dataSource.close();
    }

}